<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
            show-icon />

        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: 'ID' + '/' + '分类名称' })">
            <!-- 导入功能按钮 -->
            <el-tooltip :content="'导入'" placement="top">
                <el-button v-blur @click="handleImport" class="table-header-operate" type="success"
                    style="margin-left: 10px">
                    <Icon name="fa fa-upload" />
                    <span class="table-header-operate-text">{{ '导入' }}</span>
                </el-button>
            </el-tooltip>

            <!-- 导入模板按钮 -->
            <el-tooltip :content="'导入模板'" placement="top">
                <el-button v-blur @click="handleImportTemplate" class="table-header-operate" type="warning">
                    <Icon name="fa fa-file-text-o" />
                    <span class="table-header-operate-text">{{ '导入模板' }}</span>
                </el-button>
            </el-tooltip>

            <!-- 拉取商品按钮 -->
            <el-tooltip :content="'拉取商品'" placement="top">
                <el-button v-blur @click="handlePullGoods" class="table-header-operate" type="primary">
                    <Icon name="fa fa-download" />
                    <span class="table-header-operate-text">{{ '拉取商品' }}</span>
                </el-button>
            </el-tooltip>
        </TableHeader>

        <!-- 表格 -->
        <Table />

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { provide, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import Icon from '/@/components/icon/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import { fullUrl } from '/@/utils/common'
import axios from '/@/utils/axios'

defineOptions({
    name: 'goods/goodslist',
})

const { t } = useI18n()

// 所有商品数据
const allGoods = ref<any[]>([])

const baTable = new baTableClass(
    new baTableApi('/goods/goodslist/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('Id'), prop: 'id', align: 'center', operator: '=', operatorPlaceholder: t('Id'), width: 70 },
            { label: '缩略图', prop: 'image', align: 'center', render: 'image', operator: false },
            { label: '商品标题', prop: 'title', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query'), width: 120, showOverflowTooltip: true },
            { label: '所属分类', prop: 'category_names', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query'), width: 100 },
            { label: '所属商家', prop: 'business.name', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query'), width: 90, showOverflowTooltip: true },
            { label: '编号', prop: 'sku', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query'), showOverflowTooltip: true },
            { label: '价格', prop: 'price', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: '库存', prop: 'inventory', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: '销量', prop: 'sales', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: '浏览量', prop: 'views', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: '排序', prop: 'weight', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            {
                label: '状态',
                prop: 'status',
                align: 'center',
                render: 'switch',
                custom: { 0: 'danger', 1: 'success' },
                replaceValue: { 0: t('Disable'), 1: t('Enable') },
            },
            {
                label: '推荐',
                prop: 'istuijian',
                align: 'center',
                render: 'switch',
                custom: { 0: 'danger', 1: 'success' },
                replaceValue: { 0: t('Disable'), 1: t('Enable') },
            },
            { label: '创建时间', prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: '更新时间', prop: 'updatetime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            {
                label: '操作',
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: defaultOptButtons(['edit', 'delete']),
                operator: false,
            },
        ],
        filter: {
            page: 1,
            limit: 10,
        },
        dblClickNotEditColumn: [undefined],
    },
    {},
    {
        // 处理添加操作前的逻辑
        beforeAdd: () => {
            // 重置表单数据为默认值
            baTable.form.items = {
                ...baTable.form.defaultItems,
                name: '',
                status: 1,
                istuijian: 0,
            }
            return true
        },

        // 处理编辑操作前的逻辑
        beforeEdit: (item: any) => {
            // 仅做基础检查，不设置表单数据，让getEditData方法负责数据填充
            if (!baTable.form.items) {
                baTable.form.items = {}
            }
            console.log('准备编辑的项目ID:', item?.id)
            return true
        },

        // 处理提交前的数据处理
        beforeSubmit: (data: any) => {
            return data
        }
    },
    {
        // 处理表单提交成功后的逻辑
        afterSubmit: (res: any) => {
            // 如果提交成功，重新获取数据以更新列表
            if (res && res.code === 1) {
                // 延迟刷新，确保后端已更新数据
                setTimeout(() => {
                    baTable.getData()
                }, 300)
            }
            return res
        },

        // 处理获取编辑数据的逻辑
        getEditData: ({ res }: any) => {
            if (res && res.code === 1 && res.data) {
                console.log('编辑数据API返回:', res.data)
                // 确保表单数据对象存在
                if (!baTable.form.items) {
                    baTable.form.items = {}
                }

                // 直接使用API返回的数据填充表单
                baTable.form.items = { ...res.data }

                // 处理标签字段，确保格式正确（el-input-tag组件需要数组或逗号分隔的字符串）
                if (res.data.flag) {
                    // 如果标签是字符串，尝试转换为数组
                    if (typeof res.data.flag === 'string') {
                        // 尝试按逗号分割字符串为数组
                        const flagArray = res.data.flag.split(',').map((tag: string) => tag.trim()).filter(Boolean)
                        if (flagArray.length > 0) {
                            baTable.form.items.flag = flagArray
                        }
                    }
                    console.log('处理后的标签数据:', baTable.form.items.flag)
                }

                console.log('设置后的表单数据:', baTable.form.items)
            }
        }
    }
)

// 重写auth方法，绕过权限控制，始终返回true
baTable.auth = function () {
    return true
}

baTable.mount()
baTable.getData()

// 导入功能处理函数
const handleImport = () => {
    // 创建文件输入元素
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.xlsx,.xls'
    input.onchange = async (event: Event) => {
        const target = event.target as HTMLInputElement
        if (target.files && target.files[0]) {
            const file = target.files[0]
            const formData = new FormData()
            formData.append('file', file)

            try {
                const response = await createAxios({
                    url: getUrl() + 'goods/goodslist/importDemo',
                    method: 'post',
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })

                if (response.data.code === 1) {
                    ElMessage.success(t('Import success'))
                    baTable.getData() // 重新加载数据
                } else {
                    ElMessage.error(response.data.msg || t('Import failed'))
                }
            } catch (error) {
                ElMessage.error(t('Import failed'))
                console.error('Import error:', error)
            }
        }
    }
    input.click()
}

import { getUrl } from '/@/utils/axios'
import createAxios from '/@/utils/axios'
import { ElMessage, ElLoading } from 'element-plus'
import { getFileNameFromPath } from '/@/utils/common'

// 导入模板处理函数
const handleImportTemplate = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: t('Downloading template...'),
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        // 使用项目标准的URL构建方式
        const url = getUrl() + 'goods/goodslist/importDemo'

        // 使用axios请求获取文件数据
        const response = await createAxios({
            url,
            method: 'GET',
            responseType: 'blob', // 重要：设置响应类型为blob
            timeout: 30000 // 30秒超时
        })

        // 从响应头中提取文件名，增加安全性检查
        let fileName = 'goods_import_template.xlsx'

        // 安全地访问headers
        if (response.headers) {
            // 尝试多种可能的content-disposition头名称（考虑大小写）
            const contentDisposition =
                response.headers['content-disposition'] ||
                response.headers['Content-Disposition'] ||
                response.headers['CONTENT-DISPOSITION']

            if (contentDisposition) {
                try {
                    const match = contentDisposition.match(/filename[^;=]*=((['"]).*?\2|[^;]*)/)
                    if (match && match[1]) {
                        fileName = match[1].replace(/['"]/g, '')
                        // 安全地解码URL编码文件名
                        try {
                            fileName = decodeURIComponent(fileName)
                        } catch (e) {
                            console.warn('Failed to decode filename, using original:', fileName)
                        }
                    }
                } catch (e) {
                    console.warn('Error parsing content-disposition:', e)
                }
            }
        }

        // 创建Blob对象，安全地访问content-type
        let contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // 默认Excel类型

        if (response.headers) {
            // 尝试多种可能的content-type头名称（考虑大小写）
            contentType =
                response.headers['content-type'] ||
                response.headers['Content-Type'] ||
                response.headers['CONTENT-TYPE'] ||
                contentType
        }

        const blob = new Blob([response.data], {
            type: contentType
        })

        // 创建下载链接
        const downloadLink = document.createElement('a')
        const href = URL.createObjectURL(blob)
        downloadLink.href = href
        downloadLink.download = fileName

        // 触发下载
        document.body.appendChild(downloadLink)
        downloadLink.click()

        // 清理资源
        setTimeout(() => {
            document.body.removeChild(downloadLink)
            URL.revokeObjectURL(href)
        }, 100)

        ElMessage.success(t('Template downloaded successfully'))
    } catch (error) {
        ElMessage.error(t('Download template failed'))
        console.error('Download template error:', error)
    } finally {
        loading.close()
    }
}

// 拉取商品处理函数
const handlePullGoods = () => {
    ElMessageBox.confirm(t('Are you sure to pull goods?'), t('Pull goods'), {
        confirmButtonText: t('Confirm'),
        cancelButtonText: t('Cancel'),
        type: 'warning'
    }).then(async () => {
        try {
            const response = await axios({
                url: '/goods/goodslist/get_ggapi_goods',
                method: 'post'
            })

            if (response.data.code === 1) {
                ElMessage.success(t('Pull success'))
                baTable.getData() // 重新加载数据
            } else {
                ElMessage.error(response.data.msg || t('Pull failed'))
            }
        } catch (error) {
            ElMessage.error(t('Pull failed'))
            console.error('Pull goods error:', error)
        }
    }).catch(() => {
        ElMessage.info(t('Pull canceled'))
    })
}

// 提供baTable实例和商品数据
provide('baTable', baTable)
provide('allGoods', allGoods)
</script>

<style scoped lang="scss"></style>
